package mini.ideashare.cms.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 这是一个测试的接口
 */
@CrossOrigin
@Controller
public class FileController extends AbstractBaseController {

    private static Map<String /* format */, String /* contentType */> formatMap = new HashMap<String, String>();

    String BASE_PATH = "/Users/lixiang/files/books/";

    static{
        formatMap.put("png", "image/png");
        formatMap.put("gif", "image/gif");
        formatMap.put("webp", "image/webp");
        formatMap.put("jpg", "image/jpeg");
        formatMap.put("jpeg", "image/jpeg");
    }
    /**
     * 上传文件的接口
     * @return
     */
//    @PostMapping("/utils/uploadImage")
//    @ResponseBody
//    public Map<String, String> uploadImage(MultipartHttpServletRequest request, HttpServletResponse response){
//
////        request.setCharacterEncoding("utf-8");
////        response.setCharacterEncoding("utf-8");
//        MultipartFile requestFile = request.getFile("upfile");
//
//
//
//        String newName  = this.getName(requestFile.getOriginalFilename());
//        String url = newName;
//        String callback = request.getParameter("callback");
//
//
//        BufferedInputStream in = null;
//        try {
//            in = new BufferedInputStream(requestFile.getInputStream());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String currentPath = System.getProperty("user.dir")+"/image/";
//
//
//        File file = new File(currentPath+newName);
//
//        FileOutputStream out = null;
//        try {
//            out = new FileOutputStream( file );
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        BufferedOutputStream output = new BufferedOutputStream(out);
//        try {
//            in.transferTo(output);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        String nowUrl = "file/getFile?fileName="+url;
//
//        Map<String,String> map = new HashMap<>();
//        map.put("name",newName);
//        map.put("originalName",requestFile.getOriginalFilename());
//        map.put("size", String.valueOf(requestFile.getSize()));
//        map.put("state","SUCCESS");
//        map.put("type",requestFile.getContentType());
//        map.put("url",nowUrl);
//        String result = "{\"name\":\""+ newName +"\", \"originalName\": \""+ requestFile.getOriginalFilename() +"\", \"size\": "+ requestFile.getSize() +", \"state\": \""+ "SUCCESS" +"\", \"type\": \""+ requestFile.getContentType() +"\", \"url\": \""+ nowUrl +"\"}";
//
//        result = result.replaceAll( "\\\\", "\\\\" );
//
//        if( callback == null ){
//            return (map);
//        }else{
//            try {
//                response.getWriter().print("<script>"+ callback +"(" + result + ")</script>");
//                return null;
//            } catch (IOException e) {
//                e.printStackTrace();
//                return null;
//            }
//        }
//
//    }
//    /**
//     * 上传文件的接口
//     * @return
//     */
//    @PostMapping("/utils/uploadImage")
//    @ResponseBody
//    public Map<String, Object> uploadImage(MultipartFile file, HttpServletResponse response){
//
////        request.setCharacterEncoding("utf-8");
////        response.setCharacterEncoding("utf-8");
//        MultipartFile requestFile = file;
//
//
//
//        String newName  = this.getName(requestFile.getOriginalFilename());
//        String url = newName;
//
//
//        BufferedInputStream in = null;
//        try {
//            in = new BufferedInputStream(requestFile.getInputStream());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String currentPath = System.getProperty("user.dir")+"/image/";
//
//
//        File file2 = new File(currentPath+newName);
//
//        FileOutputStream out = null;
//        try {
//            out = new FileOutputStream( file2 );
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        BufferedOutputStream output = new BufferedOutputStream(out);
//        try {
//            in.transferTo(output);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        String nowUrl = "file/getFile?fileName="+url;
//
//        Map<String,Object> map = new HashMap<>();
//        map.put("errno","0");
//        map.put("data", Arrays.asList(nowUrl));
//
//        return (map);
//
//
//    }
    /**
     * 获取文件的接口
     * @return
     */
    @GetMapping("/file/getFile")
    public void getFile(@RequestParam("fileName") String name, HttpServletResponse response){

        //取文件的后缀名
        String suffix = name.split("\\.")[1];
        OutputStream os = null;
        String currentPath = System.getProperty("user.dir")+"/image/";
        String fileName = currentPath +name;
        File file = new File(fileName);
        FileInputStream is = null;
        try {
            response.setContentType(formatMap.get(suffix));
            is = new FileInputStream(file);
            final int fileSize = Long.valueOf(is.getChannel().size()).intValue();
            // 返回结果缓冲区
            byte[] buffer = new byte[fileSize];

            os = response.getOutputStream();
            int length;
            while ((length = is.read(buffer, 0, fileSize)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null != is){
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                is = null;
            }
            if(null != os){
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                os = null;
            }
        }

    }

    /**
     * 依据原始文件名生成新文件名
     * @return
     */
    private String getName(String fileName) {
        Random random = new Random();
        return "" + random.nextInt(10000)
                + System.currentTimeMillis() + this.getFileExt(fileName);
    }

    /**
     * 根据字符串创建本地目录 并按照日期建立子目录返回
     * @param path
     * @return
     */
    private String getFolder(String path, HttpServletRequest request) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        path += "/" + formater.format(new Date());
        File dir = new File(this.getPhysicalPath(path,request));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {

                return "";
            }
        }
        return path;
    }

    /**
     * 根据传入的虚拟路径获取物理路径
     *
     * @param path
     * @return
     */
    private String getPhysicalPath(String path, HttpServletRequest request) {
        String servletPath = request.getServletPath();
        String realPath = request.getSession().getServletContext()
                .getRealPath(servletPath);
        return new File(realPath).getParent() +"/" +path;
    }
    /**
     * 获取文件扩展名
     *
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }


}
